#!/bin/bash
# =========================================
# 🚀 Docker 挂载目录权限修复 + 批量添加可执行权限（排除自身脚本）
# =========================================

set -e

echo "🔧 脚本开始执行..."

# ===============================
# 1️⃣ 修复挂载目录权限
# ===============================
fix_permissions() {
    echo "🔹 修复 Docker 容器挂载目录权限..."

    declare -A dirs=(
        ["./mysql"]="999:999"
        ["./mongodb7"]="999:999"
        ["./redis7"]="999:999"
        ["./rabbitmq"]="999:999"
        ["./elasticsearch"]="1000:1000"
        ["./kafka"]="1000:1000"
        ["./nacos/logs"]="1001:1001"
    )

    for dir in "${!dirs[@]}"; do
        if [ -d "$dir" ]; then
            chown -R ${dirs[$dir]} "$dir"
            echo "✅ $dir 权限已设置为 ${dirs[$dir]}"
        else
            echo "⚠️ 目录不存在: $dir"
        fi
    done

    # RabbitMQ 特殊处理
    mkdir -p ./rabbitmq/plugins
}

# ===============================
# 2️⃣ 批量给当前目录平级 .sh 文件添加可执行权限（排除自身脚本）
# ===============================
make_sh_executable() {
    echo "🔹 设置当前目录平级 .sh 文件可执行权限（排除自身脚本）..."

    current_script="$(basename "$0")"

    for file in ./*.sh; do
        if [ -f "$file" ] && [ "$(basename "$file")" != "$current_script" ]; then
            chmod +x "$file"
            echo "✅ $file 已添加可执行权限"
        fi
    done
}

# ===============================
# 主程序
# ===============================
fix_permissions
make_sh_executable

echo "🎉 脚本执行完成，所有权限已更新"
